import '../../public.dart';
import 'form_validator.dart';

class SellGiftCardDetailModel extends ViewStateModel {
  final int cardTypeId;
  final String cardTypeName;

  String? selectedSubcategory;
  int? selectedSubcategoryId;
  SysGiftCardCategoryEntity? selectedSubcategoryEntity;
  String cardAmount = '';
  double cashValue = 0.0;
  List<File> uploadedImages = [];
  String cardCode = '';
  bool isLoading = false;
  bool isLoadingSubcategories = false; // 新增：用于加载子类别时的加载状态
  List<SysGiftCardCategoryEntity> subcategories = [];
  CurrentMaxQuoteDto? currentMaxQuote; // 存储从API获取的报价信息

  // 汇率，默认值
  double? exchangeRate;

  // 验证错误信息
  String? _lastValidationError;

  SellGiftCardDetailModel({
    required this.cardTypeId,
    required this.cardTypeName,
    SysGiftCardCategoryEntity? defaultCategory,
  }) {
    selectedSubcategoryEntity = defaultCategory;
    selectedSubcategoryId = defaultCategory?.id;
    selectedSubcategory = defaultCategory?.categoryName;
  }

  void init() async {
    // 获取子类别数据
    await loadSubcategories();
    // 获取报价信息
    await loadMaxQuotation();
    notifyListeners();
  }

  // 加载子类别数据
  Future<void> loadSubcategories() async {
    setLoadingSubcategories(true);
    try {
      final response = await GiftcardApi.categoryListByType_2(cardTypeId);
      subcategories = response.content ?? [];
    } catch (e) {
      debugPrint('Error loading subcategories: $e');
    } finally {
      setLoadingSubcategories(false);
    }
  }

  // 获取当前最高报价
  Future<void> loadMaxQuotation() async {
    try {
      // 只有当已选择子类别时才调用API
      if (selectedSubcategoryId != null) {
        final response = await SellCardApi.queryMaxQuotation(
          cardTypeId: cardTypeId,
          cardCategoryId: selectedSubcategoryId!,
        );
        currentMaxQuote = response.content!;
        // 使用 price * rate * discount 计算汇率，然后抹零
        if (currentMaxQuote!.price != null &&
            currentMaxQuote!.rate != null &&
            currentMaxQuote!.discount != null) {
          final price = double.tryParse(currentMaxQuote!.price!) ?? 0.0;
          final rate = double.tryParse(currentMaxQuote!.rate!) ?? 0.0;
          final discount = double.tryParse(currentMaxQuote!.discount!) ?? 0.0;

          // 计算: price * rate * discount，然后抹零（不四舍五入）
          final calculatedRate = (price * rate * discount);
          exchangeRate = calculatedRate.floorToDouble(); // 直接抹零
          // 重新计算现金价值
          calculateCashValue();
        }
      } else {
        debugPrint('No subcategory selected yet');
      }
    } catch (e) {
      debugPrint('Error loading quotation: $e');
    }
  }

  // 设置子类别
  void setSubcategory(String subcategory, {int? categoryId}) async {
    selectedSubcategory = subcategory;
    selectedSubcategoryId = categoryId;

    // 根据categoryId找到对应的子类别实体
    if (categoryId != null) {
      try {
        selectedSubcategoryEntity = subcategories.firstWhere(
          (item) => item.id == categoryId,
        );
      } catch (e) {
        // 如果通过ID没找到，尝试通过名称查找
        selectedSubcategoryEntity = subcategories.firstWhere(
          (item) => item.categoryName == subcategory,
          orElse: () => SysGiftCardCategoryEntity(),
        );
      }
    } else if (subcategory.isNotEmpty) {
      // 如果没有categoryId，尝试通过名称查找
      selectedSubcategoryEntity = subcategories.firstWhere(
        (item) => item.categoryName == subcategory,
        orElse: () => SysGiftCardCategoryEntity(),
      );
    }

    // 重置金额和现金价值，因为minimum可能已经改变
    cardAmount = '';
    cashValue = 0.0;

    // 清除之前的验证错误
    _lastValidationError = null;

    // 获取新的报价信息（异步处理）
    try {
      await loadMaxQuotation();
    } catch (e) {
      debugPrint('Error loading quotation in setSubcategory: $e');
    }
    notifyListeners();
  }

  // 设置卡金额
  void setCardAmount(String amount) {
    cardAmount = amount;
    calculateCashValue();
    _lastValidationError = validateAmount(); // 实时验证
    notifyListeners();
  }

  // 计算现金价值
  void calculateCashValue() {
    if (cardAmount.isNotEmpty) {
      final amount = double.tryParse(cardAmount) ?? 0.0;
      final rate = exchangeRate ?? 0.0;

      if (amount > 0 && rate > 0) {
        cashValue = amount * rate;
      } else {
        cashValue = 0.0;
      }
    } else {
      cashValue = 0.0;
    }
  }

  // 添加图片
  void addImage(File image) {
    uploadedImages.add(image);
    notifyListeners();
  }

  // 移除图片
  void removeImage(int index) {
    uploadedImages.removeAt(index);
    notifyListeners();
  }

  // 设置卡号
  void setCardCode(String code) {
    cardCode = code;
    notifyListeners();
  }

  // 设置加载状态
  void setLoading(bool loading) {
    isLoading = loading;
    notifyListeners();
  }

  // 设置子类别加载状态
  void setLoadingSubcategories(bool loading) {
    isLoadingSubcategories = loading;
    notifyListeners();
  }

  // 验证金额是否满足minimum要求
  String? validateAmount() {
    // 基础验证：金额不能为空
    if (cardAmount.isEmpty) {
      _lastValidationError = 'Amount is required';
      return _lastValidationError;
    }

    // 转换金额为数字
    final amount = double.tryParse(cardAmount);
    if (amount == null) {
      _lastValidationError = 'Please enter a valid amount';
      return _lastValidationError;
    }

    // 检查金额是否为负数
    if (amount <= 0) {
      _lastValidationError = 'Amount must be greater than 0';
      return _lastValidationError;
    }

    // 检查是否小于minimum
    final minimum = selectedSubcategoryEntity?.minimum;
    if (minimum != null && minimum > 0) {
      if (amount < minimum) {
        _lastValidationError = 'Minimum amount is $minimum';
        return _lastValidationError;
      }
    }

    // 验证通过，清除错误
    _lastValidationError = null;
    return null;
  }

  // 获取当前验证错误
  String? get currentValidationError => _lastValidationError;

  // 验证表单
  bool validateForm() {
    return FormValidator.validateSubcategory(selectedSubcategory) == null &&
        validateAmount() == null &&
        FormValidator.validateImages(uploadedImages) == null &&
        FormValidator.validateRequired(cardCode, 'card code') == null;
  }

  // 上传图片
  Future<List<String>> _uploadImages() async {
    if (uploadedImages.isEmpty) {
      return [];
    }

    try {
      // 并行上传所有图片
      final uploadFutures = uploadedImages.map((imageFile) async {
        try {
          final response = await FileUpApi.upload(
            catalogType: CatalogType.mobileUserSellCard,
            file: imageFile,
          );
          return response.content;
        } catch (e) {
          debugPrint('Error uploading image: $e');
          return null;
        }
      });

      // 等待所有上传任务完成
      final results = await Future.wait(uploadFutures);

      // 过滤掉空结果
      return results.where((url) => url != null).cast<String>().toList();
    } catch (e) {
      debugPrint('Error in _uploadImages: $e');
      throw Exception('Failed to upload images: $e');
    }
  }

  // 提交售卡请求
  Future<bool> submitSellCard(BuildContext context) async {
    setLoading(true);
    try {
      // 先上传图片
      final cardUrlList = await _uploadImages();

      // 使用 currentMaxQuote 中的值来构建请求参数，移除无关逻辑
      final params = SellGiftCardDto(
        cardTypeId: cardTypeId,
        cardCategoryId: selectedSubcategoryId ?? 0,
        cardAmount: int.tryParse(cardAmount) ?? 0,
        cashValue: cashValue.toInt(),
        price: currentMaxQuote?.price ?? '0.0',
        rate: currentMaxQuote?.rate ?? '0.0',
        discount: currentMaxQuote?.discount ?? '0.0',
        cardCodeList: [cardCode],
        cardUrlList: cardUrlList,
      );
      // 实际应该调用SellCardApi中相应的方法
      await SellCardApi.sell(params);
      resetForm();
      return true;
    } catch (e) {
      if (context.mounted) {
        Toast.show('Error: $e');
      }
      return false;
    } finally {
      setLoading(false);
    }
  }

  // 重置表单
  void resetForm() {
    selectedSubcategory = null;
    cardAmount = '';
    cashValue = 0.0;
    uploadedImages.clear();
    cardCode = '';
    isLoading = false;
    notifyListeners();
  }

  @override
  void dispose() {
    uploadedImages.clear();
    super.dispose();
  }
}
